<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="./lib/bootstrap.css" />
  <script src="./lib/jquery.js"></script>
</head>

<body>
  <!-- 1. 文件选择框 -->
  <input type="file" id="file1" />
  <!-- 2. 上传文件的按钮 -->
  <button id="btnUpload">上传文件</button>

  <!-- bootstrap 中的进度条 -->
  <div class="progress" style="width: 500px; margin: 15px 10px;">
    <div class="progress-bar progress-bar-striped active" style="width: 0%" id="percent">
      0%
    </div>
  </div>

  <br />

  <!-- 3. img 标签，来显示上传成功以后的图片 -->
  <img src="" alt="" id="img" width="800" />

  <script>

    // 接口地址： http://www.liulongbin.top:3006/api/upload/avatar
 const btnUpload = document.querySelector('#btnUpload')
    const fileInput = document.querySelector('#file1')

    // 2. 为按钮绑定单击事件处理函数
    btnUpload.addEventListener('click', function () {
      if(fileInput.files.length===0){
        return alert('请选择文件')
      }
      const fd =new FormData()
      fd.append('avatar',fileInput.files[0])
      const xhr = new XMLHttpRequest()
    // 1. 获取到文件上传按钮
   
    // 2. 为按钮绑定单击事件处理函数
      xhr.upload.onprogress    =function (e) {
      // 进度条
      if (e.lengthComputable) {
        const res = Math.ceil(e.loaded/e.total*100)
        console.log(res);
        percent.style.width=`${res}%`
        percent.innerHTML=`${res}%`
      }
    }
    xhr.upload.onload=function(){
      $('#percent').removeClass().addClass('progress-bar progress-bar-success ')
    }
   
  xhr.open('POST','http://www.liulongbin.top:3006/api/upload/avatar')
    xhr.send(fd)
    xhr.onreadystatechange =function(){
      if (xhr.readyState===4 &&xhr.status===200) {
        console.log(JSON.parse(xhr.responseText));
        const {statu,message,url} = JSON.parse(xhr.responseText)
        img.src = `http://www.liulongbin.top:3006${url}`
      }
    }
      // 3. 获取到用户选择的文件列表
    })
  </script>
</body>

</html>